package com.atguigu.gmall.scheduled.job.handler;

import com.atguigu.gmall.scheduled.mapper.CartMapper;
import com.atguigu.gmall.scheduled.pojo.Cart;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Component
public class CartJobHandler {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private CartMapper cartMapper;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    private static final String EXCEPTION_KEY = "cart:exception";
    private static final String KEY_PREFIX = "cart:info:";

    @XxlJob("cartSyncData")
    public ReturnT<String> syncData(String param){
        BoundSetOperations<String, String> setOps = this.redisTemplate.boundSetOps(EXCEPTION_KEY);
        if (setOps.size()==0){
            return ReturnT.SUCCESS;
        }
        String userId = setOps.pop();

        while (userId != null){
            //1.删除mysql中的购物车
            this.cartMapper.delete(new QueryWrapper<Cart>().eq("user_id",userId));

            //2.读取当前用户redis中的购物车
            BoundHashOperations<String, Object, Object> hasOps = this.redisTemplate.boundHashOps(KEY_PREFIX + userId);
            List<Object> cartJsons = hasOps.values();
            //3.如果redis购物车为空就直接结束
            if (CollectionUtils.isEmpty(cartJsons)){
                return ReturnT.SUCCESS;
            }
            //4.如果redis中数据库不为空，则新增到mysql数据库中
            cartJsons.forEach(cartJson->{
                try {
                    Cart cart = MAPPER.readValue(cartJson.toString(), Cart.class);
                    this.cartMapper.insert(cart);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }

            });

            userId = setOps.pop();
        }


        return ReturnT.SUCCESS;
    }
}
